
package com.bds.portal.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Criteria;
import org.springframework.stereotype.Component;

import com.bds.model.Hosts;
import com.bds.model.Project;
import com.bds.portal.common.result.Page;
import com.bds.portal.util.Const;

@Component
public class HostService {

	private static Logger logger = Logger.getLogger(HostService.class);

	@Resource
	private NutDao portalDao;

	public Page getHostList(Long user_id, Integer pageNum, Integer pageSize, Long pid) {
		Pager pager = portalDao.createPager(pageNum, pageSize);
		Criteria cri = Cnd.cri();
		cri.where().andEquals("user_id", user_id);
		if (pid != null) {
			cri.where().andEquals("project_id", pid);
		}
		List<Hosts> list = portalDao.query(Hosts.class, cri, pager);
		for (Hosts h : list) {
			Project p = portalDao.fetch(Project.class, Cnd.where("id", "=", h.getProject_id()));
			if (p != null) {
				h.setProject_name(p.getProject_name());
			}
		}
		int count = portalDao.count(Hosts.class, cri);
		Page p = new Page(count, pager.getPageNumber(), pager.getPageSize());
		p.setCode(Const.SUC);
		p.setData(list);
		return p;

	}

	public List<Hosts> getHostAllList(Long user_id, Long pid) {

		Criteria cri = Cnd.cri();
		cri.where().andEquals("user_id", user_id);
		if (pid != null) {
			cri.where().andEquals("project_id", pid);
		}
		List<Hosts> list = portalDao.query(Hosts.class, cri);

		return list;

	}

	public Hosts saveHosts(Long user_id, Long project_id, String website) {

		try {

			Hosts p = new Hosts();
			p.setCreate_time(new Date());
			p.setProject_id(project_id);
			p.setUser_id(user_id);
			p.setWebsite(website);
			portalDao.fastInsert(p);
			return p;
		} catch (Exception e) {
			logger.error("", e);
			return null;
		}

	}

	public Hosts getHosts(Long id) {
		Hosts p = portalDao.fetch(Hosts.class, Cnd.where("id", "=", id));
		return p;
	}

	public Hosts getHostsByUrl(Long user_id, String website) {
		Hosts p = portalDao.fetch(Hosts.class, Cnd.where("user_id", "=", user_id).and("website", "=", website));
		return p;
	}

}
